#include "hal_sci.h"
#include "driverlib.h"
#include "device.h"

void hal_sci_init(uint32_t base, uint32_t lspclk, uint32_t baudrate)
{
    // 配置GPIO为SCI A功能
    if (base == SCIA_BASE) {
        GPIO_setPinConfig(DEVICE_GPIO_CFG_SCIRXDA);
        GPIO_setDirectionMode(DEVICE_GPIO_PIN_SCIRXDA, GPIO_DIR_MODE_IN);
        GPIO_setPadConfig(DEVICE_GPIO_PIN_SCIRXDA, GPIO_PIN_TYPE_STD);
        GPIO_setQualificationMode(DEVICE_GPIO_PIN_SCIRXDA, GPIO_QUAL_ASYNC);

        GPIO_setPinConfig(DEVICE_GPIO_CFG_SCITXDA);
        GPIO_setDirectionMode(DEVICE_GPIO_PIN_SCITXDA, GPIO_DIR_MODE_OUT);
        GPIO_setPadConfig(DEVICE_GPIO_PIN_SCITXDA, GPIO_PIN_TYPE_STD);
        GPIO_setQualificationMode(DEVICE_GPIO_PIN_SCITXDA, GPIO_QUAL_ASYNC);
    }
    // 如需支持SCIB等，可按需添加

    // 初始化SCI外设
    SCI_performSoftwareReset(base);
    SCI_setConfig(base, lspclk, baudrate, (SCI_CONFIG_WLEN_8 | SCI_CONFIG_STOP_ONE | SCI_CONFIG_PAR_NONE));
    SCI_resetChannels(base);
    SCI_resetRxFIFO(base);
    SCI_resetTxFIFO(base);
    SCI_enableFIFO(base);
    SCI_enableModule(base);
    SCI_performSoftwareReset(base);
}

void hal_sci_send_byte(uint32_t base, uint8_t data)
{
    SCI_writeCharBlockingFIFO(base, data);
}

void hal_sci_send_buffer(uint32_t base, const uint8_t *data, uint32_t len)
{
    for (uint32_t i = 0; i < len; ++i) {
        hal_sci_send_byte(base, data[i]);
    }
}

int hal_sci_recv_byte(uint32_t base)
{
    if (SCI_getRxFIFOStatus(base) > 0) {
        return SCI_readCharBlockingFIFO(base);
    }
    return -1;
}
